package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ApCollectionService;
import com.heima.article.service.AuthorService;
import com.heima.common.constants.article.ArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.behavior.BehaviorFeign;
import com.heima.feigns.user.UserFeign;
import com.heima.model.article.dto.ArticleDto;
import com.heima.model.article.dto.ArticleHomeDto;
import com.heima.model.article.dto.ArticleInfoDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.behavior.dtos.ApArticleRelationDto;
import com.heima.model.article.pojos.ApCollection;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.utils.threadlocal.AppUserThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    AuthorService authorService;
    @Autowired
    ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    ApArticleContentMapper apArticleContentMapper;
    @Autowired
    ApArticleMapper apArticleMapper;
    @Autowired
    BehaviorFeign behaviorFeign;
    @Autowired
    UserFeign userFeign;
    @Autowired
    ApCollectionService apCollectionService;




    @Value("${file.oss.web-site}")
    String webSite;

    @Override
    @Transactional
    public ResponseResult saveArtilce(ArticleDto articleDto) {
        //验证参数
        if (articleDto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //封装article对象
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(articleDto, apArticle);
        //根据作者名称查询作者id
        ApAuthor apAuthor = authorService.getOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getName, articleDto.getAuthorName()));
        if (apAuthor == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章作者不存在");
        }
        apArticle.setAuthorId(Long.valueOf(apAuthor.getId()));
        //判断文章是否存在
        if (apArticle.getId() == null) {
            // 普通文章
            apArticle.setComment(0);
            apArticle.setViews(0);
            apArticle.setCollection(0);
            apArticle.setLikes(0);
            save(apArticle);
        } else {
            ApArticle one = getById(apArticle.getId());
            if (one == null) {
                log.error("对应文章id的文章不存在，文章id为==>{}", apArticle.getId());
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章数据不存在");
            }
            //删除中间表相关信息
            apArticleConfigMapper.delete(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId, apArticle.getId()));
            apArticleContentMapper.delete(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, apArticle.getId()));
            updateById(apArticle);
        }
        //插入中间表文章配置表
        //保存article_config 数据
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsComment(true);
        apArticleConfig.setIsDown(false);
        apArticleConfig.setIsDelete(false);
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfigMapper.insert(apArticleConfig);
        //添加文章内容
        //保存文章article_content 数据
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setContent(articleDto.getContent());
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContentMapper.insert(apArticleContent);
        //返回文章ID
        return ResponseResult.okResult(apArticle.getId());
    }

    /**
     * 根据参数加载文章列表
     *
     * @param loadtype 1为加载更多  2为加载最新
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDto dto) {
        //参数校验
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (dto.getSize() == null || dto.getSize() < 1 || dto.getSize() > 50) {
            dto.setSize(10);
        }
        //设置频道id信息
        if (dto.getTag() == null) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        //判断请求参数中的时间
        if (dto.getMaxBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        //判断查询类型
        if (loadtype == null || (loadtype.equals(ArticleConstants.LOADTYPE_LOAD_MORE) && loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW))) {
            loadtype = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        //查询文章列表
        List<ApArticle> apArticleList = apArticleMapper.loadArticleList(dto, loadtype);
        ResponseResult responseResult = ResponseResult.okResult(apArticleList);
        responseResult.setHost(webSite);
        return responseResult;
    }

    /**
     * 加载文章详情
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleInfo(ArticleInfoDto dto) {
        //参数校验
        if (dto == null || dto.getArticleId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        Long articleId = dto.getArticleId();
        ApArticleConfig apArticleConfig = apArticleConfigMapper.selectOne(
                Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId, articleId));
        if (apArticleConfig == null || apArticleConfig.getIsDelete() || apArticleConfig.getIsDown()) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章已下架");
        }
        //根据文章id查询文章内容和文章配置
        ApArticleContent apArticleContent = apArticleContentMapper.selectOne(
                Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, articleId));
        if (apArticleContent == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章内容信息不存在");
        }
        Map map = new HashMap();
        map.put("config", apArticleConfig);
        map.put("content", apArticleContent);
        return ResponseResult.okResult(map);
    }

    /**
     * 获取文章中用户的行为数据
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
        Map resultMap = new HashMap();
        resultMap.put("islike", false);
        resultMap.put("isunlike", false);
        resultMap.put("isfollow", false);
        resultMap.put("iscollection", false);
        //参数校验
        if (dto == null || dto.getArticleId() == null || dto.getAuthorId() == null) {
            return ResponseResult.okResult(resultMap);
        }
        //判断用户的登录状态
        ApUser user = AppUserThreadLocalUtils.getUser();
        ApArticleRelationDto apArticleRelationDto = new ApArticleRelationDto();
        if(user!=null){
            //用户登录
            apArticleRelationDto.setEntryId(user.getId());
            apArticleRelationDto.setType((short)1);
            //判断是否关注了作者,只有登录用户才能关注作者
            ApUserFollow apUserFollow = userFeign.findByUserIdAndFollowId(user.getId(), dto.getAuthorId());
            if(apUserFollow!=null){
                resultMap.put("isfollow",true);
            }
        }else {
            //设备id登录
            apArticleRelationDto.setEntryId(dto.getEquipmentId());
            apArticleRelationDto.setType((short)0);
        }
        apArticleRelationDto.setArticleId(dto.getArticleId());
        //远程调用方法查询是否点赞和不喜欢
        Map map = behaviorFeign.findApArticleRelation(apArticleRelationDto);
        resultMap.putAll(map);
        //判断是否收藏
        ApCollection apCollection = apCollectionService.getOne(Wrappers.<ApCollection>lambdaQuery()
                .eq(ApCollection::getArticleId, dto.getArticleId())
                .eq(ApCollection::getEntryId, map.get("entryId")));
        if(apCollection!=null){
            resultMap.put("iscollection",true);
        }
        return ResponseResult.okResult(resultMap);

    }
}
